import * as mysql from 'mysql2/promise';
import {ConfigService} from '@nestjs/config';

// 定义类型
interface DbConfig {
    host: string;
    port: number;
    user: string;
    password: string;
    database: string;
}

// 创建连接池的工厂函数
export const createConnectionPool = (configService: ConfigService): mysql.Pool => {
    // 添加运行时检查（推荐！生产可用）
    const getRequired = (key: string): string => {
        const value = configService.get<string>(key);
        if (!value) {
            throw new Error(`Missing required environment variable: ${key}`);
        }
        return value;
    };
    const dbConfig: DbConfig = {
        host: getRequired('DB_HOST'),
        port: configService.get<number>('DB_PORT', {infer: true}) || 3306,
        user: getRequired('DB_USER'),
        password: getRequired('DB_PASSWORD'),
        database: getRequired('DB_NAME'),
    };

    // 适合开发阶段       !  告诉 TypeScript：“我确定这个值不会是 undefined”
    // const dbConfig: DbConfig = {
    //     host: configService.get<string>('DB_HOST')!,
    //     port: configService.get<number>('DB_PORT', {infer: true}) || 3306,
    //     user: configService.get<string>('DB_USER')!,
    //     password: configService.get<string>('DB_PASSWORD')!,
    //     database: configService.get<string>('DB_NAME')!,
    // };

    return mysql.createPool(dbConfig);
};

// 连接配置（生产环境用  .env  管理）
// const pool = mysql.createPool({
//     host: 'localhost',
//     port: 3306,
//     user: 'root',
//     password: '123456',
//     database: 'nest-base',
//     waitForConnections: true,
//     connectionLimit: 10,
//     queueLimit: 0,
// })
// export default pool;